package com.zz.demo.thread;

import org.assertj.core.api.ThrowableAssert;

import java.util.concurrent.locks.ReentrantLock;

public class FairLock {
    public static void main(String[] args) {
        final MyService myService = new MyService(false);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("线程名：" + Thread.currentThread().getName() + "运行了");
                myService.serviceMethod();
            }
        };

        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }

    }
}

class MyService {
    private ReentrantLock lock;

    public MyService(Boolean isFair) {
        this.lock = new ReentrantLock(isFair);
    }
    public void serviceMethod() {
        try {
            lock.lock();
            System.out.println("线程名：" + Thread.currentThread().getName() + "获得锁定");
        } finally {
            lock.unlock();
        }
    }
}
